package cn.txun.csmall.product.service.impl;

import cn.txun.csmall.commons.web.ServiceCode;
import cn.txun.csmall.commons.ex.ServiceException;
import cn.txun.csmall.product.mapper.BrandCategoryMapper;
import cn.txun.csmall.product.mapper.CategoryAttributeTemplateMapper;
import cn.txun.csmall.product.mapper.CategoryMapper;
import cn.txun.csmall.product.mapper.SpuMapper;
import cn.txun.csmall.product.pojo.entity.BrandCategory;
import cn.txun.csmall.product.pojo.entity.Category;
import cn.txun.csmall.product.pojo.entity.CategoryAttributeTemplate;
import cn.txun.csmall.product.pojo.entity.Spu;
import cn.txun.csmall.product.pojo.param.CategoryAddNewParam;
import cn.txun.csmall.product.pojo.param.CategoryUpdateInfoParam;
import cn.txun.csmall.product.pojo.vo.CategoryListItemVO;
import cn.txun.csmall.product.pojo.vo.CategoryStandardVO;
import cn.txun.csmall.product.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandCategoryMapper brandCategoryMapper;

    @Autowired
    private CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;

    @Autowired
    private SpuMapper spuMapper;

    public CategoryServiceImpl() {
        log.debug("创建业务类对象：CategoryServiceImpl");
    }

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {
        log.debug("开始处理【添加类别】的业务，参数：{}", categoryAddNewParam);
        // 应该保证此类别的名称是唯一的
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", categoryAddNewParam.getName());
        int countByName = categoryMapper.selectCount(queryWrapper);
        log.debug("根据类别名称统计匹配的类别数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "添加类别失败，类别名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 通过参数对象获取parentId
        Long parentId = categoryAddNewParam.getParentId();
        // 预设depth（深度值）为1
        Integer depth = 1;
        CategoryStandardVO parentCategory = null;
        // 判断parentId是否不为0
        if (parentId != 0) {
            // 否：调用Mapper对象的getStandardById()查询父级类别
            parentCategory = categoryMapper.getStandardById(parentId);
            // 判断查询结果（父级类别）是否为null
            if (parentCategory == null) {
                // 是：抛出异常
                String message = "添加类别失败，父级类别不存在！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            } else {
                // 否：depth（深度值）为：父级类别的depth + 1
                depth = parentCategory.getDepth() + 1;
            }
        }

        // 创建Category对象
        Category category = new Category();
        // 复制属性
        BeanUtils.copyProperties(categoryAddNewParam, category);
        // 补全Category对象的属性值：depth >>>
        category.setDepth(depth);
        // 补全Category对象的属性值：isParent >>> 固定为0
        category.setIsParent(0);
        category.setGmtCreate(LocalDateTime.now());
        category.setGmtModified(LocalDateTime.now());
        // 调用Mapper对象的insert()方法执行插入
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 判断parentId是否不为0，并判断父级类别的isParent是否为0
        if (parentId != 0 && parentCategory.getIsParent() == 0) {
            // 是：将父级类别的isParent更新为1
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            rows = categoryMapper.updateById(updateParentCategory);
            if (rows != 1) {
                String message = "添加类别失败，服务器忙，请稍后再尝试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除类别】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (currentCategory == null) {
            // 是：数据不存在，抛出异常
            String message = "删除类别失败，尝试删除的类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的isParent是否为1，如果是，则抛出异常
        if (currentCategory.getIsParent() == 1) {
            String message = "删除类别失败，该类别仍包含子级类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查此类别是否关联了品牌
        {
            QueryWrapper<BrandCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_id", id);
            int count = brandCategoryMapper.selectCount(queryWrapper);
            if (count > 0) {
                String message = "删除类别失败！当前类别仍关联了品牌！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        // 检查此类别是否关联了属性模板
        {
            QueryWrapper<CategoryAttributeTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_id", id);
            int count = categoryAttributeTemplateMapper.selectCount(queryWrapper);
            if (count > 0) {
                String message = "删除类别失败！当前类别仍关联了属性模板！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        // 检查此类别是否关联了SPU
        {

            QueryWrapper<Spu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_id", id);
            int count = spuMapper.selectCount(queryWrapper);
            if (count > 0) {
                String message = "删除类别失败！当前类别仍关联了商品！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        // 调用Mapper对象的deleteById()方法执行删除
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        // 调用Mapper对象的countByParentId方法，根据以上查询结果中的parentId，执行统计
        Long parentId = currentCategory.getParentId();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        int count = categoryMapper.selectCount(queryWrapper);
        // 判断统计结果为0，则将id不为0的父级类别的isParent更新为0
        if (count == 0 && parentId!=0) {
            Category parentCategory = new Category();
            parentCategory.setId(parentId);
            parentCategory.setIsParent(0);
            rows = categoryMapper.updateById(parentCategory);
            if (rows != 1) {
                String message = "删除类别失败，服务器忙，请稍后再尝试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
    }
    @Override
    public void updateInfoById(Long id, CategoryUpdateInfoParam categoryUpdateInfoParam) {
        log.debug("开始处理【修改类别详情】的业务，参数ID：{}, 新数据：{}", id, categoryUpdateInfoParam);
        // 检查类别是否存在，如果不存在，则抛出异常
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = categoryMapper.selectCount(queryWrapper);
        log.debug("根据类别ID统计匹配的类别数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查类别名称是否被其它类别占用，如果被占用，则抛出异常
        QueryWrapper<Category> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", categoryUpdateInfoParam.getName())
                .ne("id", id);
        int countByName = categoryMapper.selectCount(queryWrapper2);
        log.debug("根据类别名称统计匹配的类别数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改类别详情失败，类别名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行修改
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateInfoParam, category);
        category.setId(id);
        int rows = categoryMapper.updateById(category);
        if (rows != 1) {
            String message = "修改类别详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的类别数据更新入到数据库，完成！");
    }

    @Override
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", parentId);
        int count = categoryMapper.selectCount(queryWrapper);
        if (count == 0 && parentId!=0 ) {
            String message = "该分类已经被删除！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        return categoryMapper.listByParentId(parentId);
    }

    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    private void updateEnableById(Long id, Integer enable) {
        // 调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (currentCategory == null) {
            String message = ENABLE_TEXT[enable] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的enable与参数enable是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (currentCategory.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "类别失败，此类别已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category对象
        Category updateCategory = new Category();
        // 向Category对象中封装属性值：id, enable，均来自方法参数
        updateCategory.setId(id);
        updateCategory.setEnable(enable);
        // 调用Mapper对象的update()方法执行更新
        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }


}